<template>
<div id="cart" v-if="userInfo.token">
    <!--头部区域-->
    <header class="titleWrapper">
        <h4><strong>购物车</strong></h4>
        <button class="clearCart" @click="clearCart">清空购物车</button>
    </header>
    <div class="contentWrapper">
        <!--中间内容-->
        <main class="contentWrapperList">
            <section>
                <div class="shopCartListCon" v-for="(goods,index) in shopCart" :key="goods.id">
                    <div class="left" v-if="goods.checked===1">
                        <a 
                             href="javascript:;" 
                             class="cartCheckBox"
                             :checked="true" 
                             @click.stop="singerGoodsSelected(goods.id)"
                             >    <!--  @click.stop阻止a标签的默认事件 -->
                         </a>
                    </div>
                    <div class="left" v-else>
                        <a 
                             href="javascript:;" 
                             class="cartCheckBox"
                             :checked="false" 
                             @click.stop="singerGoodsSelected(goods.id)"
                             >    <!--  @click.stop阻止a标签的默认事件 -->
                         </a>
                    </div>
                    <div class="center">
                         <img class="image" :src="pic.small_image" alt="">   
                    </div>
                    <div class="right">
                        <a href="#">{{goods.name}}</a>
                        <div class="bottomContent">
                            <p class="shopPrice">{{goods.price|moneyFormat}}</p>
                            <div class="shopDeal">
                                <span @click="removeOutCart(goods.id,goods.num)">-</span>
                                <input disabled type="number" v-model="goods.num">
                                <span @click="addToCart(goods.id,goods.name,goods.price)">+</span>
                            </div>
                        </div>
                    </div>
                </div>
            </section>
        </main>
        <!--底部通栏-->
        <div class="tabBar">
            <div class="tabBarLeft" v-if="isSelectedAll===true">
                <a href="javascript:;" 
                class="cartCheckBox"
                :checked="true"
                @click.stop=" selectedAll(true)"
                ></a>
                <span style="font-size: 16px;">全选</span>
                <div class="selectAll">
                    合计：<span class="totalPrice">{{totalPrice|moneyFormat}}</span>
                </div>
            </div>
            <div class="tabBarLeft" v-else>
                 <a href="javascript:;" 
                 class="cartCheckBox"
                 :checked="false"
                 @click.stop=" selectedAll(false)"
                 ></a>
                 <span style="font-size: 16px;">全选</span>
                 <div class="selectAll">
                 合计：<span class="totalPrice">{{totalPrice|moneyFormat}}</span>
                 </div>
            </div>
            <div class="tabBarRight">
              <!--   <a href="#" class="pay">去结算({{goodsCount}})</a> -->
                <router-link v-if="goodsCount===0" tag="a" class="pay" :to="{name:'order',params:{totalPrice}}" style="pointer-events:none;">去结算({{goodsCount}})</router-link>
                <router-link v-else tag="a" class="pay" :to="{name:'order',params:{totalPrice}}">去结算({{goodsCount}})</router-link>            
            </div>
        </div>
    </div>
</div>
<SelectLogin v-else/>
</template>
<script>
  import {mapState,mapMutations} from 'vuex'
  import { Dialog } from 'vant';
  import SelectLogin from './../../views/login/SelectLogin'
  import {getHomeData,addGoodsToCart,removeOutCart,clearAllCart,singerGoodsSelected,selectedAll,selectedNo} from './../../service/api/index'
     export default{
       name:"Cart",
         data(){
            return {
               pic:'',
            }
           },
        computed:{
            ...mapState(["shopCart","userInfo"]),  //取state.js里面的值，因为它能够实时监控检测，所以计算属性中

            //0. 选中商品总件数
            goodsCount(){
                 let selectedGoodsCount = 0;
                 Object.values(this.shopCart).forEach((goods,index)=>{
                      if (goods.checked) {
                         selectedGoodsCount += 1;
                      }
                 });
                   return selectedGoodsCount;
            },
            
            //1.商品是否全选
            isSelectedAll(){
               let goodsCount = Object.values(this.shopCart).length;
               let tag = goodsCount>0;
               Object.values(this.shopCart).forEach((goods,index)=>{
                  if (goods.checked===0) {
                      tag = false;
                  }
               });
               return tag;
            },

             //2. 计算商品总价
             totalPrice(){
                   let totalPrice = 0;
                   Object.values(this.shopCart).forEach((goods,index)=>{
                          if (goods.checked) {
                            totalPrice += goods.price*goods.num;
                          }
                   });
                   return totalPrice;
             }
        },

       methods:{
          ...mapMutations(["REDUCE_CART","ADD_GOODS","SELECTED_SINGER_GOODS","SELECTED_ALL_GOODS","CLEAR_CART","SELECTED_NO_GOODS"]),  //拿到mutations.js  里面的REDUCE_CART方法,记得先导入  
          //1. 移除购物车
         async removeOutCart(goodsId,goodsNum){
            //（服务器端）根据goodsId，token去shopcart表查找商品，商品存在,goodsNum>1的情况下，移除，num-1；goodsNum=1情况下,移除，zhuangtai=-1,num-1
               if (goodsNum>1) {
                  let result = await removeOutCart(this.userInfo.token,goodsId);

                   console.log(result);
                   this.REDUCE_CART({goodsId});
               }else if (goodsNum === 1 ) {    //挽留
                     Dialog.confirm({
                          title: '小森温馨提示',
                          message: '确定删除该商品吗？'
                        }).then(async () => {
                           let result = await removeOutCart(this.userInfo.token,goodsId);
                           console.log(result);
                            //点了确定
                             this.REDUCE_CART({goodsId});
                        }).catch(() => {
                          // 点了取消
                          // do nothing    
                        });       
               }
           },      //   ---removeOutCart
            
            //2. 增加商品
            async addToCart(goodsId,goodsName,goodsPrice){
                  //添加商品到服务器端
               //   console.log(goodsPrice);
                  let result = await addGoodsToCart(this.userInfo.token,goodsId,goodsName,goodsPrice);
                  console.log(result);
                  if(result.status===200){
                 //存入本地
                 this.ADD_GOODS({
                    goodsId,
                    goodsName,
                    goodsPrice
                    })
                  }
            },       //   ---addToCart

            //3.单个商品选中和取消选中
             async singerGoodsSelected(goodsId){
               //  console.log(goodsId);
                  let result = await singerGoodsSelected(this.userInfo.token,goodsId);
                  if (result.status==='200') {
                     this.SELECTED_SINGER_GOODS({goodsId});
                 }
            },      //   ---singerGoodsSelected
           
            //4. 全选和取消全选
              async selectedAll(bool){
                    // this.select = !this.select;
                   //  console.log(bool);
                      if (bool===true) {
                          //当传过来的isSelected为true,也就是商品已经全部被选中，点击全选按钮取消全选，购物车所有商品的check值为0，同时同步本地
                            let result = await selectedNo(this.userInfo.token);
                            console.log(result);
                             if(result.status==='200'){
                          //     console.log(bool);   
                                this.SELECTED_ALL_GOODS(1);
                              }
                            console.log("取消了全选");
                       }else{
                          //当传过来的isSelected为false,也就是商品没有全部被选中，点击全选按钮全选，购物车所有商品的check值为1，同时同步本地
                             let result = await selectedAll(this.userInfo.token);
                             console.log(result);
                             if(result.status==='200'){
                         //  console.log("dadq");
                                   this.SELECTED_NO_GOODS(0);
                              }
                          console.log("全选");
                      }
                 //  this.SELECTED_ALL_GOODS({isSelected})
                    
            },


            //5. 清空购物车
            async clearCart(){
                  Dialog.confirm({
                          title: '小森温馨提示',
                          message: '确定清空所有商品吗？'
                        }).then(async () => {
                          //服务器清空购物车，全部商品num置为0，zhuangtrai置为-1
                           let result = await clearAllCart(this.userInfo.token);
                           console.log(result);
                            //点了确定
                            this.CLEAR_CART();
                        }).catch(() => {
                          // 点了取消
                          // do nothing
                        });
              }
      },       //  ---methods
       components:{
           SelectLogin
       },

            created(){
           
                   //暂时借用别的接口获取图片
                     getHomeData().then((response)=>{
                     if (response.success) {
                      this.pic = response.data.list[3].product_list[0];
                   // console.log(this.pic);
                   }
              }).catch(error=>{
                   // todo......
                    console.log(error);
              })
         },   //  ----createed

      
   }
</script>
<style lang="less" scoped>
      #cart{
            width: 100%;
            height: 100%;
            background-color: #f5f5f5;
        }

        .titleWrapper{
            width: 100%;
            height: 2.6rem;
            background: #fff;
            -webkit-background-size: 0.1rem 4.4rem;
            background-size: 0.1rem 4.4rem;
            position: fixed;
            left: 0;
            top: 0;
            z-index: 999;

            display: flex;
            justify-content: center;
            align-items: center;
        }

        .titleWrapper .clearCart{
           background-color:transparent;
           position:absolute;
           right:0.3rem;
           color:red;
           font-size:0.8rem;
        }

        .contentWrapper{
            padding-top: 3.5rem;
        }

        /*列表内容*/
        .contentWrapperList{
            padding-bottom: 6rem;
        }

        .contentWrapperList section{
            background-color: #fff;
        }

        .cartCheckBox{
           background: url("./images/shop-icon.png") no-repeat;
            -webkit-background-size: 2.5rem 5rem;
            background-size: 2.5rem 5rem;
            width: 1rem;
            height: 1rem;
        }

        .cartCheckBox[checked]{
            background-position: -1.2rem 0;
        }

        .shopCartListCon{
            display: flex;
            height: 6rem;
            border-bottom:  0.01rem solid #e0e0e0;
            margin-bottom: 0.7rem;
            padding: 0.5rem 0;
        }

        .shopCartListCon .left{
            /*background: purple;*/
            flex: 1;
            display: flex;
            /*justify-content: center;*/
        }

        .shopCartListCon .left a{
            display: inline-block;
            margin-top: 0.8rem;
            margin-left: 0.5rem;
        }


        .shopCartListCon .center{
            /*background: blue;*/
            flex: 3;
        }

        .shopCartListCon .center img{
            width: 100%;
            height: 100%;
        }

        .shopCartListCon .right{
            /*background: orangered;*/
            flex: 6;
            display: flex;
            flex-direction: column;
            justify-content: space-between;
            margin-left: 0.5rem;
            margin-right: 0.5rem;

            position: relative;
        }

        .shopCartListCon .right a{
            height: 2.2rem;
            line-height: 1.2rem;
            overflow: hidden;
            margin-bottom: 0.3rem;
            font-size: 0.8rem;
            color: #000;
        }

        .shopCartListCon .bottomContent{
            display: flex;
            flex-direction: row;
            justify-content: space-between;
            align-items: center;
        }

        .shopCartListCon .bottomContent .shopPrice{
            font-size: 0.8rem;
        }

        .shopCartListCon .right .shopDeal span{
            display: inline-block;
            width: 1rem;
            height: 1.2rem;
            line-height: 1.2rem;
            text-align: center;
            float: left;
        }

        .shopCartListCon .right .shopDeal input{
            float: left;
            width: 2rem;
            height: 1.2rem;
            text-align: center;
            margin: 0 0.2rem;
            font-size: 0.8rem;
        }

        /*底部通栏*/
        .tabBar{
            position: fixed;
            left:0;
            bottom:2.7rem;
            width:100%;
            height: 2.5rem;
            background-color: #fff;

            display: flex;
            justify-content: space-between;
            align-items: center;
            border-top: 0.01rem solid #e0e0e0;
        }

        .tabBarLeft{
            display: flex;
            align-items: center;
            margin-left: 0.5rem;
        }

        .tabBarLeft .selectAll{
            margin-left: 1rem;
            font-size: 1rem;
        }

        .totalPrice{
            color: #E9232C;
        }


        .tabBarRight .pay{
            width:5rem;
            height: 2rem;
            background-color: #E9232C;
            border-radius: 1rem;
            margin-right: 0.5rem;

            display: flex;
            justify-content: center;
            align-items: center;
            font-size: 1rem;
            color: #fff;
        }
</style>